import React, { useState } from "react";
import {
  Typography,
  Empty,
  Table,
  Tag,
  Space,
  Button,
  Modal,
  Spin,
} from "antd";
import { useRequest, useTitle } from "ahooks";

import styles from "./common.module.scss";

import { ExclamationCircleOutlined } from "@ant-design/icons";
import ListSearch from "../components/ListSearch";
import useLoadQuestionListData from "../../hooks/useLoadQuestionListData";
import ListPage from "../components/ListPage";
import {
  updateQuestionListService,
  deleteQuestionsService,
} from "../../services/question";
import useGetUserInfo from "../../hooks/useGetUserInfo";

const { Title } = Typography;
const { confirm } = Modal;

const Tarsh: React.FC = () => {
  useTitle("新问卷 - 回收站");
  const { userId, isAdmin } = useGetUserInfo();
  const {
    loading,
    data = {},
    refresh,
  } = useLoadQuestionListData({ isDeleted: true });
  const { list = [], total = 0 } = data;
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const { loading: recoverLoading, run: recover } = useRequest(
    async () => {
      await updateQuestionListService({ ids: selectedIds, isDeleted: false });
    },
    {
      manual: true,
      onSuccess() {
        refresh();
        setSelectedIds([]);
      },
    }
  );
  const { loading: deleteLoading, run: deleteQuestion } = useRequest(
    async () => await deleteQuestionsService(selectedIds),
    {
      manual: true,
      onSuccess() {
        refresh();
        setSelectedIds([]);
      },
    }
  );
  const tableCloumns = [
    {
      title: "标题",
      dataIndex: "title",
    },
    {
      title: "已发布",
      dataIndex: "isPublished",
      render(val: boolean) {
        return (
          <Tag color={val ? "processing" : "default"}>{val ? "是" : "否"}</Tag>
        );
      },
    },
    {
      title: "已标星",
      dataIndex: "isStar",
      render(val: boolean) {
        return (
          <Tag color={val ? "processing" : "default"}>{val ? "是" : "否"}</Tag>
        );
      },
    },
    {
      title: "已答卷",
      dataIndex: "answerCount",
    },
    {
      title: "最后修改时间",
      dataIndex: "updatedAt",
    },
  ];
  if (isAdmin)
    tableCloumns.push({
      title: "创建人",
      dataIndex: "createdBy",
      render(val) {
        if (val) return <Tag color="success">{val}</Tag>;
        return <></>;
      },
    });

  function del() {
    confirm({
      title: "确定彻底删除吗？",
      content: "请谨慎处理",
      icon: <ExclamationCircleOutlined />,
      onOk: () => {
        deleteQuestion();
      },
    });
  }

  const TableElement = (
    <>
      <div>
        <Space style={{ marginBottom: "16px" }}>
          <Button
            type="primary"
            disabled={!selectedIds.length}
            onClick={recover}
            loading={recoverLoading}
          >
            恢复
          </Button>
          <Button
            type="primary"
            danger
            disabled={!selectedIds.length}
            onClick={del}
            loading={deleteLoading}
          >
            彻底删除
          </Button>
        </Space>
        <Table
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          dataSource={list.map((i: any) => {
            if (userId === i.createdId) delete i.createdBy;
            return i;
          })}
          columns={tableCloumns}
          pagination={false}
          rowKey="id"
          rowSelection={{
            type: "checkbox",
            onChange(selectedRowKeys) {
              setSelectedIds(selectedRowKeys as string[]);
            },
          }}
        />
      </div>
    </>
  );

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>回收站</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.main}>
        {loading ? (
          <div style={{ textAlign: "center" }}>
            <Spin />
          </div>
        ) : (
          <div>
            {list.length ? TableElement : <Empty description="暂无数据" />}
          </div>
        )}
        <div className={styles.footer}>
          {!loading && <ListPage total={total} />}
        </div>
      </div>
    </>
  );
};
export default Tarsh;
